const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const compression = require('compression');
const path = require('path');

// 导入路由
const authRoutes = require('../routes/auth');
const userRoutes = require('../routes/users');
const productRoutes = require('../routes/products');
const cartRoutes = require('../routes/cart');
const orderRoutes = require('../routes/orders');

// 导入中间件
const errorHandler = require('../middleware/errorHandler');

const app = express();

// 基础中间件
app.use(helmet()); // 安全性中间件
app.use(cors()); // 跨域中间件
app.use(compression()); // 压缩中间件
app.use(morgan('combined')); // 日志中间件

// 解析中间件
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 正确的路由配置
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);
app.use('/api/cart', cartRoutes);
app.use('/api/orders', orderRoutes);

// 健康检查
app.get('/health', (req, res) => {
    res.json({ 
        status: 'OK', 
        message: 'EShop API is running',
        timestamp: new Date().toISOString()
    });
});

// 404 处理 - 使用 use 方法处理所有未匹配的路由
app.use((req, res, next) => {
    res.status(404).json({
        success: false,
        message: `路由 ${req.originalUrl} 不存在`
    });
});

// 全局错误处理
app.use(errorHandler);

module.exports = app;